package com.softline.documentsmall.utils;

import com.google.common.collect.Lists;
import com.softline.documentsmall.entity.EntryDetails;
import com.softline.documentsmall.entity.EntryDetailsSubmit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.List;

/**
 * 类与类之间属性值copy
 * @author zhongweicheng
 * @date 2020/9/10 16:47
 */
@Slf4j
public class VoTransferUtils {

    /**
     * vo相同属性之间值传递
     * @param source
     * @return
     */
    public static  Object transferVo(Object source){
        Object target = null;
        if(source instanceof EntryDetailsSubmit){
            //EntryDetailsSubmit转成EntryDetails
            EntryDetails details = new EntryDetails();
            BeanUtils.copyProperties(source,details);
            target = details;
        }else if(source instanceof EntryDetails){
            //EntryDetails转成EntryDetailsSubmit
            EntryDetailsSubmit entryDetailsSubmit = new EntryDetailsSubmit();
            BeanUtils.copyProperties(source,target);
            target = entryDetailsSubmit;
        }
        return target;
    }


    //获取最近五年的日期
    public static List<Integer> getFiveYear(){
        List<Integer> y = Lists.newArrayList();
        Calendar c = Calendar.getInstance();
        int curYear = c.get(Calendar.YEAR);
        for(int i = 0;i<5;i++){
            y.add(curYear);
            curYear--;
        }
        return y;
    }


    /**
     * 根据地址获得数据的输入流
     * @param strUrl 网络连接地址
     * @return url的输入流
     */
    public static InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), output);
            return new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
            log.error(e + "");
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                log.error(e + "");
            }
        }
        return null;
    }
}
